package cn.edu.cug.cs.gtl.plugins.h3dfile.layer;

import cn.edu.cug.cs.gtl.api.wrapper.TableWrapper;
import cn.edu.cug.cs.gtl.api.wrapper.TupleWrapper;
import cn.edu.cug.cs.gtl.apis.ui.AbstractApplication;
import cn.edu.cug.cs.gtl.apis.ui.actions.AbstractAction;
import cn.edu.cug.cs.gtl.io.FileDataSplitter;
import cn.edu.cug.cs.gtl.protos.Layer;
import cn.edu.cug.cs.gtl.protos.Table;
import cn.edu.cug.cs.gtl.protos.Tuple;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Locale;
import java.util.ResourceBundle;

public class ExportAsCSVAction extends AbstractAction {
    @Override
    public void initialize(AbstractApplication theApp) {
        ResourceBundle resourceBundle = ResourceBundle.getBundle("h3dfile_resource", Locale.getDefault());

        name=resourceBundle.getString("popupmenu.model3d.layer.export_as_csv");
        menuItem.setText(name);


        this.theApp = theApp;
        menuItem.addActionListener(this);
        theApp.getMainFrame().getProjectPanel().getTreeComponent().getLayerNodePopupMenu().add(menuItem);
    }

    /**
     * Invoked when an action occurs.
     *
     * @param e the event to be processed
     */
    @Override
    public void actionPerformed(ActionEvent e) {


        final JFileChooser ivFileChooser = new JFileChooser(
                //new File(SoPreferences.getValue("OIVJHOME") + File.separator + "data" + File.separator + "models"));
                new File(System.getProperty("user.dir")) );
        ivFileChooser.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                if ( f == null )
                    return false;
                if ( f.isDirectory() )
                    return true;
                return f.getName().toLowerCase().endsWith(".csv");
            }

            @Override
            public String getDescription() {
                return "CSV File";
            }
        });

        ivFileChooser.removeChoosableFileFilter(ivFileChooser.getAcceptAllFileFilter());

        if ( ivFileChooser.showSaveDialog(null) != JFileChooser.APPROVE_OPTION )
            return;
        String fileName = ivFileChooser.getSelectedFile().getAbsolutePath();
        try {
            Layer layer = theApp.getCurrentLayer();
            if(layer!=null){
                Table table = layer.getAttributeTable();
                if(table!=null){
                    TableWrapper tableWrapper = new TableWrapper(table);
                    tableWrapper.exportToCSV(new cn.edu.cug.cs.gtl.io.File(fileName), FileDataSplitter.SEMICOLON);

                }
            }

        }
        catch (Exception exception){
            exception.printStackTrace();
        }
    }


    public boolean exportToCSV(Table.Builder builder, cn.edu.cug.cs.gtl.io.File csvFile,  FileDataSplitter splitter){
        try {
            FileWriter fw = new FileWriter(csvFile);
            int rows = builder.getTupleCount();
            int cols = builder.getInfo().getColumnInfoCount();
            for(int c=0;c<cols;++c){
                fw.write(builder.getInfo().getColumnInfo(c).getName());
                if(c<cols-1)
                    fw.write(splitter.getDelimiter());
            }
            fw.write("\n");
            for(int r=0;r<rows;++r){
                Tuple t = builder.getTuple(r);
                TupleWrapper tupleWrapper = new TupleWrapper(t);
                for(int c=0;c<cols;++c){

                    String s = t.getElement(c).toString();

                    if(s!=null)
                        fw.write(s);

                    if(c<cols-1)
                        fw.write(splitter.getDelimiter());
                }
                fw.write("\n");
            }
            fw.close();
            return true;
        }
        catch (IOException e){
            e.printStackTrace();
        }

        return false;
    }
}
